package com.feng.seata.service;

import com.feng.common.enums.CommonErrorCode;
import com.feng.common.enums.ErrorCode;
import com.feng.common.exception.BizException;
import com.feng.seata.dto.OrderDto;
import com.feng.seata.mapper.ProductMapper;
import com.feng.seata.tcc.action.IStockTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class ProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private IStockTccAction stockTccAction;

    @Transactional(rollbackFor = Exception.class)
    public void minusStock(Integer buyNum) {
        productMapper.minusStock(buyNum);
    }

    public void deductStock(OrderDto orderDto) {
        boolean result = stockTccAction.prepareDeductStock(null, orderDto.getProductId(), orderDto.getBuyNum());
        if (!result) {
            throw new BizException(CommonErrorCode.APP_BIZ_ERROR);
        }
    }

}
